<?php
// 引入头部
require_once 'includes/header.php';

// 检查权限 - 只有管理员可以访问
if (!$current_user || $current_user['role'] !== 'admin') {
    header('Location: /POS/index.php');
    exit;
}

// 定义设置项
$setting_groups = [
    'basic' => [
        'title' => '基础设置',
        'icon' => 'fas fa-store',
        'settings' => [
            'shop_name' => [
                'title' => '店铺名称',
                'type' => 'text',
                'description' => '显示在收据和页面标题上的店铺名称'
            ],
            'shop_address' => [
                'title' => '店铺地址',
                'type' => 'textarea',
                'description' => '显示在收据上的店铺地址'
            ],
            'shop_phone' => [
                'title' => '联系电话',
                'type' => 'text',
                'description' => '店铺联系电话'
            ],
            'shop_logo' => [
                'title' => '店铺Logo',
                'type' => 'image',
                'description' => '上传店铺Logo（推荐尺寸: 200x200像素）'
            ]
        ]
    ],
    'order' => [
        'title' => '订单设置',
        'icon' => 'fas fa-clipboard-list',
        'settings' => [
            'order_prefix' => [
                'title' => '订单号前缀',
                'type' => 'text',
                'description' => '生成的订单号前缀，如"ORD-"'
            ],
            'tax_rate' => [
                'title' => '税率',
                'type' => 'number',
                'description' => '销售税率百分比（如：9.5表示9.5%）',
                'step' => '0.01',
                'min' => '0',
                'max' => '100'
            ],
            'receipt_footer' => [
                'title' => '收据页脚文字',
                'type' => 'textarea',
                'description' => '显示在收据底部的文字，如感谢语或退款政策'
            ]
        ]
    ],
    'member' => [
        'title' => '会员设置',
        'icon' => 'fas fa-users',
        'settings' => [
            'points_rate' => [
                'title' => '积分比例',
                'type' => 'number',
                'description' => '每消费1元获得的积分数量',
                'step' => '0.01',
                'min' => '0'
            ],
            'member_discount' => [
                'title' => '会员折扣',
                'type' => 'number',
                'description' => '会员折扣百分比（如：90表示9折）',
                'step' => '0.1',
                'min' => '0',
                'max' => '100'
            ]
        ]
    ],
    'display' => [
        'title' => '显示设置',
        'icon' => 'fas fa-desktop',
        'settings' => [
            'items_per_page' => [
                'title' => '每页显示数量',
                'type' => 'number',
                'description' => '列表页每页显示的记录数量',
                'min' => '5',
                'max' => '100',
                'step' => '5'
            ],
            'currency_symbol' => [
                'title' => '货币符号',
                'type' => 'text',
                'description' => '显示价格的货币符号，如"¥"或"$"'
            ],
            'date_format' => [
                'title' => '日期格式',
                'type' => 'select',
                'options' => [
                    'Y-m-d' => 'YYYY-MM-DD (2023-12-31)',
                    'd/m/Y' => 'DD/MM/YYYY (31/12/2023)',
                    'm/d/Y' => 'MM/DD/YYYY (12/31/2023)',
                    'Y年m月d日' => 'YYYY年MM月DD日 (2023年12月31日)'
                ],
                'description' => '系统中显示日期的格式'
            ]
        ]
    ]
];

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $updated_settings = $_POST['settings'] ?? [];
    $updated_files = $_FILES['settings'] ?? [];
    
    foreach ($setting_groups as $group_key => $group) {
        foreach ($group['settings'] as $setting_key => $setting) {
            // 处理文本类型设置
            if (isset($updated_settings[$setting_key]) && $setting['type'] !== 'image') {
                $value = $updated_settings[$setting_key];
                
                // 验证数字类型
                if ($setting['type'] === 'number') {
                    $value = floatval($value);
                    if (isset($setting['min']) && $value < floatval($setting['min'])) {
                        $value = floatval($setting['min']);
                    }
                    if (isset($setting['max']) && $value > floatval($setting['max'])) {
                        $value = floatval($setting['max']);
                    }
                }
                
                // 更新设置
                $sql = "INSERT INTO settings (setting_key, setting_value) 
                        VALUES (?, ?) 
                        ON DUPLICATE KEY UPDATE setting_value = ?";
                Database::query($sql, [$setting_key, $value, $value]);
            }
            
            // 处理图片上传
            if ($setting['type'] === 'image' && 
                isset($updated_files['name'][$setting_key]) && 
                $updated_files['error'][$setting_key] === UPLOAD_ERR_OK) {
                
                $file_name = $updated_files['name'][$setting_key];
                $file_tmp = $updated_files['tmp_name'][$setting_key];
                $file_size = $updated_files['size'][$setting_key];
                $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
                
                // 验证扩展名
                $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
                if (in_array($file_ext, $allowed_ext)) {
                    $upload_dir = __DIR__ . '/../uploads/settings/';
                    
                    // 如果目录不存在则创建
                    if (!file_exists($upload_dir)) {
                        mkdir($upload_dir, 0777, true);
                    }
                    
                    $new_file_name = $setting_key . '_' . time() . '.' . $file_ext;
                    $upload_path = $upload_dir . $new_file_name;
                    
                    if (move_uploaded_file($file_tmp, $upload_path)) {
                        $file_url = '/uploads/settings/' . $new_file_name;
                        
                        // 更新设置
                        $sql = "INSERT INTO settings (setting_key, setting_value) 
                                VALUES (?, ?) 
                                ON DUPLICATE KEY UPDATE setting_value = ?";
                        Database::query($sql, [$setting_key, $file_url, $file_url]);
                    }
                }
            }
        }
    }
    
    $_SESSION['alert'] = [
        'type' => 'success',
        'message' => '设置已成功保存'
    ];
    
    // 重定向以避免刷新时重复提交
    header('Location: /POS/settings.php');
    exit;
}

// 获取所有设置值
$settings = [];
$sql = "SELECT setting_key, setting_value FROM settings";
$result = Database::fetchAll($sql);

foreach ($result as $row) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// 设置默认值
$defaults = [
    'shop_name' => '餐饮收银系统',
    'tax_rate' => '9.0',
    'points_rate' => '1',
    'member_discount' => '90',
    'items_per_page' => '10',
    'currency_symbol' => '¥',
    'date_format' => 'Y-m-d'
];

foreach ($defaults as $key => $value) {
    if (!isset($settings[$key])) {
        $settings[$key] = $value;
    }
}

// 当前活动的设置组
$active_group = $_GET['group'] ?? 'basic';
if (!isset($setting_groups[$active_group])) {
    $active_group = 'basic';
}
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-6">
            <h1 class="h3 mb-0">系统设置</h1>
            <p class="text-muted">配置系统参数和选项</p>
        </div>
    </div>
    
    <div class="row">
        <div class="col-md-3">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">设置菜单</h5>
                </div>
                <div class="list-group list-group-flush">
                    <?php foreach ($setting_groups as $group_key => $group): ?>
                    <a href="?group=<?php echo $group_key; ?>" class="list-group-item list-group-item-action <?php echo $active_group === $group_key ? 'active' : ''; ?>">
                        <i class="<?php echo $group['icon']; ?> mr-2"></i> <?php echo $group['title']; ?>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        
        <div class="col-md-9">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="<?php echo $setting_groups[$active_group]['icon']; ?> mr-2"></i> <?php echo $setting_groups[$active_group]['title']; ?></h5>
                </div>
                <div class="card-body">
                    <form action="" method="POST" enctype="multipart/form-data">
                        <?php foreach ($setting_groups[$active_group]['settings'] as $setting_key => $setting): ?>
                        <div class="form-group">
                            <label for="<?php echo $setting_key; ?>"><?php echo $setting['title']; ?></label>
                            
                            <?php if ($setting['type'] === 'text'): ?>
                            <input type="text" class="form-control" id="<?php echo $setting_key; ?>" name="settings[<?php echo $setting_key; ?>]" value="<?php echo htmlspecialchars($settings[$setting_key] ?? ''); ?>">
                            
                            <?php elseif ($setting['type'] === 'number'): ?>
                            <input type="number" class="form-control" id="<?php echo $setting_key; ?>" name="settings[<?php echo $setting_key; ?>]" 
                                value="<?php echo htmlspecialchars($settings[$setting_key] ?? ''); ?>"
                                <?php if (isset($setting['min'])): ?>min="<?php echo $setting['min']; ?>"<?php endif; ?>
                                <?php if (isset($setting['max'])): ?>max="<?php echo $setting['max']; ?>"<?php endif; ?>
                                <?php if (isset($setting['step'])): ?>step="<?php echo $setting['step']; ?>"<?php endif; ?>>
                            
                            <?php elseif ($setting['type'] === 'textarea'): ?>
                            <textarea class="form-control" id="<?php echo $setting_key; ?>" name="settings[<?php echo $setting_key; ?>]" rows="3"><?php echo htmlspecialchars($settings[$setting_key] ?? ''); ?></textarea>
                            
                            <?php elseif ($setting['type'] === 'select' && isset($setting['options'])): ?>
                            <select class="form-control" id="<?php echo $setting_key; ?>" name="settings[<?php echo $setting_key; ?>]">
                                <?php foreach ($setting['options'] as $option_value => $option_label): ?>
                                <option value="<?php echo $option_value; ?>" <?php echo ($settings[$setting_key] ?? '') === $option_value ? 'selected' : ''; ?>>
                                    <?php echo $option_label; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            
                            <?php elseif ($setting['type'] === 'image'): ?>
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="<?php echo $setting_key; ?>" name="settings[<?php echo $setting_key; ?>]" accept="image/*">
                                <label class="custom-file-label" for="<?php echo $setting_key; ?>">选择文件</label>
                            </div>
                            <?php if (!empty($settings[$setting_key])): ?>
                            <div class="mt-2">
                                <img src="<?php echo htmlspecialchars($settings[$setting_key]); ?>" alt="<?php echo $setting['title']; ?>" class="img-thumbnail" style="max-height: 100px;">
                            </div>
                            <?php endif; ?>
                            
                            <?php endif; ?>
                            
                            <small class="form-text text-muted"><?php echo $setting['description']; ?></small>
                        </div>
                        <?php endforeach; ?>
                        
                        <div class="form-group mt-4">
                            <button type="submit" class="btn btn-primary">保存设置</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 显示提示消息
document.addEventListener('DOMContentLoaded', function() {
    <?php if (isset($_SESSION['alert'])): ?>
    showAlert('<?php echo $_SESSION['alert']['message']; ?>', '<?php echo $_SESSION['alert']['type']; ?>');
    <?php unset($_SESSION['alert']); ?>
    <?php endif; ?>
    
    // 显示已选文件名
    document.querySelectorAll('.custom-file-input').forEach(function(input) {
        input.addEventListener('change', function() {
            var fileName = this.files[0] ? this.files[0].name : '选择文件';
            this.nextElementSibling.textContent = fileName;
        });
    });
});
</script>

<?php
// 引入页脚
require_once 'includes/footer.php';
?> 